import { createRouter, createWebHashHistory } from "vue-router";
import Login from "@/components/Login.vue";
import Detail from "@/components/ProductDetail.vue";
import Edit from "@/components/Edit.vue";
import {jwtDecode} from "jwt-decode";

//存储全局用户
window.whenUser = {};

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "Index",
      component: Login,
    },
    {
      path: "/detail/:id",
      name: "Detail",
      component: Detail,
    },
    {
      path: "/e/:id",
      name: "Edit",
      component: Edit,
    },
  ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem("token"); // 从 localStorage 获取 token
  console.log("Navigating to:", to.fullPath);
  if (to.meta.requiresAuth && !isTokenValid(isAuthenticated)) {
    // 如果目标路由需要认证且用户未认证，重定向到登录页面
    next({ name: "Login" });
  } else {
    next(); // 继续路由导航
  }
});

// 检查 token 是否有效
function isTokenValid(token) {
  try {
    const decoded = jwtDecode(token);
    const currentTime = Date.now() / 1000; // 当前时间（单位：秒）
    window.whenUser = decoded
    console.log(decoded.exp)
    return decoded.exp > currentTime
  } catch (error) {
    console.error("Token decode error:", error);
    return false; // 解码失败，认为 token 无效
  }
}

//是否登录且登录有效
export function isLogin(){
  const isAuthenticated = localStorage.getItem("token"); // 从 localStorage 获取 token
  return isTokenValid(isAuthenticated)
}

export function ExitLogin(){
  localStorage.clear();
}

export default router;
